package com.nova.android.tvlauncher.utils

import android.database.Cursor
import android.util.Log
import androidx.tvprovider.media.tv.TvContractCompat
import com.nova.android.tvlauncher.bean.atv_bean.HomeChannelDto
import com.nova.android.tvlauncher.bean.atv_bean.HomeProgramDto
import com.shudong.lib_base.ext.appContext
import com_github_lib_base.ext.getAppNameWithCache

data class Channel(
    val id: Long,
    val fields: Map<String, Any?> // 存储所有字段
)

data class PreviewProgram(
    val id: Long,
    val channelId: Long,
    val fields: Map<String, Any?>
)

object TvRepository {
    fun getChannels(): List<Channel> {
        val channels = mutableListOf<Channel>()
        val uri = TvContractCompat.Channels.CONTENT_URI
        // 不指定 projection，查询所有字段

        try {
            appContext.contentResolver.query(uri, null, null, null, null)?.use { cursor ->
                while (cursor.moveToNext()) {
                    val id = cursor.getLong(cursor.getColumnIndexOrThrow(TvContractCompat.Channels._ID))
                    val fields = mutableMapOf<String, Any?>()

                    // 遍历所有字段
                    cursor.columnNames.forEach { columnName ->
                        val columnIndex = cursor.getColumnIndex(columnName)
                        if (columnIndex >= 0) { // 确保列索引有效
                            val value = when (cursor.getType(columnIndex)) {
                                Cursor.FIELD_TYPE_NULL -> null
                                Cursor.FIELD_TYPE_INTEGER -> cursor.getLong(columnIndex)
                                Cursor.FIELD_TYPE_FLOAT -> cursor.getDouble(columnIndex)
                                Cursor.FIELD_TYPE_STRING -> cursor.getString(columnIndex)
                                Cursor.FIELD_TYPE_BLOB -> "BLOB data"
                                else -> "Unknown type"
                            }
                            fields[columnName] = value
                            //Log.d("TvRepository", "Channel ID: $id, Field: $columnName, Value: $value")
                        } else {
                            Log.w("TvRepository", "Channel column not found: $columnName")
                            fields[columnName] = null
                        }
                    }

                    channels.add(Channel(id, fields))
                }
            }
        } catch (e: SecurityException) {
            Log.e("TvRepository", "Permission denied: ${e.message}")
        }

        return channels
    }

    fun getPreviewPrograms(channelId: Long): List<PreviewProgram> {
        val programs = mutableListOf<PreviewProgram>()
        val uri = TvContractCompat.PreviewPrograms.CONTENT_URI
        val selection = "${TvContractCompat.PreviewPrograms.COLUMN_CHANNEL_ID} = ?"
        val selectionArgs = arrayOf(channelId.toString())

        try {
            appContext.contentResolver.query(uri, null, selection, selectionArgs, null)?.use { cursor ->
                while (cursor.moveToNext()) {
                    val id = cursor.getLong(cursor.getColumnIndexOrThrow(TvContractCompat.PreviewPrograms._ID))
                    val chanId = cursor.getLong(cursor.getColumnIndexOrThrow(TvContractCompat.PreviewPrograms.COLUMN_CHANNEL_ID))
                    val fields = mutableMapOf<String, Any?>()

                    // 遍历所有字段
                    cursor.columnNames.forEach { columnName ->
                        val columnIndex = cursor.getColumnIndex(columnName)
                        if (columnIndex >= 0) { // 确保列索引有效
                            val value = when (cursor.getType(columnIndex)) {
                                Cursor.FIELD_TYPE_NULL -> null
                                Cursor.FIELD_TYPE_INTEGER -> cursor.getLong(columnIndex)
                                Cursor.FIELD_TYPE_FLOAT -> cursor.getDouble(columnIndex)
                                Cursor.FIELD_TYPE_STRING -> cursor.getString(columnIndex)
                                Cursor.FIELD_TYPE_BLOB -> "BLOB data"
                                else -> "Unknown type"
                            }
                            fields[columnName] = value
                            //Log.d("TvRepository", "Program ID: $id, Field: $columnName, Value: $value")
                        } else {
                            Log.w("TvRepository", "Program column not found: $columnName")
                            fields[columnName] = null
                        }
                    }

                    programs.add(PreviewProgram(id, chanId, fields))
                }
            }
        } catch (e: SecurityException) {
            Log.e("TvRepository", "Permission denied: ${e.message}")
        }

        return programs
    }

    fun getChannelData():MutableList<HomeChannelDto>{
        val list = getChannels()
        val channelList = mutableListOf<HomeChannelDto>()
        list.forEach {
            val programList =getPreviewPrograms(it.id)
            if(programList.isNotEmpty()){
                val channelId = it.fields.get("_id") as Long
                val channelName = it.fields.get("display_name") as String
                val packageName = it.fields.get("package_name") as String
                val intentUrl = it.fields.get("app_link_intent_uri") as String?
                val homeChannelDto = HomeChannelDto()
                homeChannelDto.channelId = channelId
                homeChannelDto.channelName = if(packageName.contains("youtube"))"${packageName.getAppNameWithCache()}：$channelName" else channelName.toString()
                homeChannelDto.packageName = packageName.toString()
                homeChannelDto.intentUrl = intentUrl.toString()
                val list = mutableListOf<HomeProgramDto>()
                programList.forEach {
                    val programId = it.fields.get("_id") as Long?
                    val title = it.fields.get("title") as String?
                    val programTitle = title
                    val programDesc = it.fields.get("short_description") as String?
                    val programCover = it.fields.get("poster_art_uri") as String?
                    val programIntentUrl = it.fields.get("intent_uri") as String?
                    val programDto = HomeProgramDto()
                    programDto.programId = programId
                    programDto.programTitle = programTitle.toString()
                    programDto.programDesc = programDesc.toString()
                    programDto.programCover = programCover.toString()
                    programDto.intentUrl = programIntentUrl.toString()
                    list.add(programDto)
                }
                homeChannelDto.programList = list
                channelList.add(homeChannelDto)
            }
        }
        return channelList
    }
}